package grape.file.service.cloudstorage.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.request.DelFileRequest;
import com.qcloud.cos.request.GetFileInputStreamRequest;
import com.qcloud.cos.request.UploadFileRequest;
import com.qcloud.cos.sign.Credentials;
import grape.common.tools.IoStreamTool;
import grape.common.tools.PathTool;
import grape.file.service.cloudstorage.config.QcloudStorageConfig;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Auther: wzn
 * @Date: 2019/2/20 15:39
 * @Description: 腾讯云存储
 */
@Service
public class QcloudCloudStorageServiceImpl extends AbstractCloudStorageService  implements InitializingBean {
    @Autowired
    private QcloudStorageConfig config;
    private COSClient client;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 如果没有配置不初始化，保证服务能正常启动
        if (config.getAppId() == null) {
            return;
        }
        Credentials credentials = new Credentials(config.getAppId(), config.getSecretId(),
                config.getSecretKey());

        //初始化客户端配置
        ClientConfig clientConfig = new ClientConfig();
        //设置bucket所在的区域，华南：gz 华北：tj 华东：sh
        clientConfig.setRegion(config.getRegion());

        client = new COSClient(clientConfig, credentials);
    }
    @Override
    public boolean support(String type) {
        return isEqual(config.uploadType(),type);
    }

    @Override
    public String upload(byte[] data, String filepath) {
        //腾讯云必需要以"/"开头
        filepath = PathTool.ensureBeginSlash(filepath);
        //上传到腾讯云
        UploadFileRequest request = new UploadFileRequest(config.getBucketName(), PathTool.concat(config.getPrefix() , filepath), data);
        String response = client.uploadFile(request);

        JSONObject parse = JSONUtil.parseObj(response);
        if(parse.getInt("code") != 0) {
            throw new RuntimeException("腾讯云文件上传失败," + response);
        }

        return getResult(config.getDomain() ,config.getPrefix() , filepath);
    }

    @Override
    public String uploadSuffix(byte[] data,String prefixPath, String suffix) {
        return upload(data, newPath(PathTool.concat( prefixPath), suffix));
    }

    @Override
    public String upload(InputStream inputStream, String filepath) {
        try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, filepath);
        } catch (IOException e) {
            throw new RuntimeException("腾讯云文件上传失败," + e.getMessage(),e);
        }
    }

    @Override
    public String uploadSuffix(InputStream inputStream,String prefixPath, String suffix) {
        return upload(inputStream, newPath(PathTool.concat( prefixPath), suffix));
    }

    @Override
    public byte[] download(String objectName) throws Exception {
        InputStream fileInputStream = client.getFileInputStream(new GetFileInputStreamRequest(config.getBucketName(), objectName));
        return IoStreamTool.inputStreamToByteArray(fileInputStream);
    }

    @Override
    public int delete(String objectName) {
        String s = client.delFile(new DelFileRequest(config.getBucketName(), objectName));
        return 1;
    }

}
